<template>
    <el-dialog
      @close="close"
      :title="title"
      :visible.sync="dialog"
      :close-on-click-modal="false"
      width="600px">
        <el-form ref="formInline" size="mini" :rules="rules" :model="formInline" label-width="100px">
            <el-form-item prop="title" label="推荐位文案">
                <el-input placeholder="请输入推荐位文案" v-model="formInline.title"></el-input>
            </el-form-item>
            <el-form-item prop="file" label="推荐位图片">
                <el-upload
                  class="upload-demo"
                  action="https://jsonplaceholder.typicode.com/posts/"
                  :on-change="handleChange"
                  :on-remove="handleRemove"
                  :file-list="fileList"
                  list-type="picture"
                  :auto-upload="false"
                  :limit="1">
                    <el-button size="small" type="primary" :disabled="fileList.length >= 1">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                </el-upload>
            </el-form-item>
            <el-form-item prop="link" label="关联房间">
                <el-input placeholder="关联房间" v-model="formInline.link"></el-input>
            </el-form-item>
            <el-form-item prop="time" label="展示时间：">
                <el-radio v-model="limitTime" @change="limitTimeChange" :label="0">期限展示</el-radio>
                <el-radio v-model="limitTime" @change="limitTimeChange" :label="1">不限制时间</el-radio>
                <div v-if="limitTime === 0">
                    <el-date-picker class="input_s"  v-model="formInline.begintime" type="datetime" placeholder="" @change="timeChange" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
                    <el-date-picker class="input_s"  v-model="formInline.endtime" type="datetime" placeholder="" @change="timeChange" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
                </div>
            </el-form-item>
            <!-- <el-form-item prop="statustype" label="是否展示">
                <el-radio v-model="formInline.statustype" label="0">展示</el-radio>
                <el-radio v-model="formInline.statustype" label="1">未展示</el-radio>
            </el-form-item> -->
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button :disabled="btnLoading" @click="dialog = false">取 消</el-button>
            <el-button type="primary" :loading="btnLoading" @click="onSubmit()">确 定</el-button>
        </span>
    </el-dialog>
</template>
<script>
import { addUserAPI, getDetailAPI ,updateAdminAPI } from '@/api/user';
import { addRecommendhall, editRecommendhall } from '@/api/teamhall';
import { upload, formatFile } from '@/utils/other-request';
import { mapGetters } from 'vuex';
export default {
    name: 'RoomEdit',
    props: {
        dialog_: {
            default: false,
            type: Boolean
        },
        type: {
            default: "",
            type: String
        },
        model: {
            default: null,
            type: Object
        }
    },
    computed: {
        ...mapGetters([
            'img_base_url',
        ]),
        title() {
            return this.type === "add" ? "新增房间推荐位" : "编辑房间推荐位";
        }
    },
    data() {
        // 表单验证
        let validateFile = (rule, value, callback) => {
            if (this.fileList.length === 0) {
                callback(new Error("请选择上传图片"));
            } else {
                callback();
            }
        }

        let validateTime = (rule, value, callback) => {
            if (this.limitTime === 1) {
                callback();
            }
            if (this.formInline.begintime && this.formInline.endtime) {
                callback();
            } else {
                callback(new Error("请选择起止时间"));
            }
        }
        return {
            fileList: [],
            dialog: true,
            limitTime: 0, // 0 期限展示  1不限制时间
            temporary: {
                begintime: "", // 展示开始时间
                endtime: "" // 展示结束时间
            },
            btnLoading: false,  // 提交按钮状态
            formInline: {
                hallid: 1,
                title:'', // 推荐位文案
                link:'', // 关联房间
                photo:'', // 推荐背景图地址
                statustype:'1', // 0：展示   1：不展示
                linktype: '2', // 1：外链 2：房间
                plattypes:'0', // 0：所有端
                begintime: "", // 展示开始时间
                endtime: "" // 展示结束时间
            },
            btnLoading: false,
            roleList: [],
            rules: {
                title: [
                    { required: true, message: '请输入推荐位文案', trigger: 'blur' }
                ],
                file:[
                    { validator: validateFile, trigger: 'blur' }
                ],
                link: [
                    { required: true, message: '请输入房间号', trigger: 'blur' }
                ],
                time: [
                    { validator: validateTime, trigger: 'change' }
                ]
            }
        }
    },
    mounted() {
        this.dialog = this.dialog_;
        if (this.type === "edit") {
            for (var i in this.formInline) {
                if (["title", "photo", "link", "begintime", "endtime"].includes(i)) {
                    this.formInline[i] = this.model[i];
                }
            }
            this.formInline.id = this.model.id;
            const obj = {
                name: "edit." + this.model.photo.split(".")[this.model.photo.split(".").length - 1],
                url: this.img_base_url + this.model.photo
            };
            this.fileList.push(obj);
            if (this.formInline.begintime === "" && this.formInline.endtime === "") {
                this.limitTime = 1;
            }
        }
    },
    methods: {
        // 关闭弹窗
        close() {
            this.$emit('close');
        },
        handleRemove(file, fileList) {
            this.fileList = [];
            fileList.forEach(item => {
                let fileItem = {
                    name: item.name,
                    url: item.url
                }
                this.fileList.push(fileItem);
            });
        },
        handleChange(file, fileList) {
            this.fileList = [];
            fileList.forEach(item => {
                let fileItem = {
                    name: item.name,
                    url: item.url
                }
                this.fileList.push(fileItem);
            });
            this.formInline.photo = fileList[0].raw;
            this.handleVerify("file");
        },
        // 处理表单验证
        handleVerify(name) {
            this.$refs["formInline"]["validateField"](name);
        },
        timeChange() {
            this.handleVerify("time");
        },
        // 添加房间推荐位
        addBanner() {
            this.btnLoading = true;
            addRecommendhall(this.formInline).then(res => {
                this.btnLoading = false;
                console.log(res)
                if (res.code === 0) {
                    this.$message.success('操作成功');
                    this.dialog = false;
                    this.$emit('success');
                } else {
                    this.$message.error(res.message);
                }
            });
        },
        // 编辑房间推荐位
        editBanner() {
            this.btnLoading = true;
            console.log(this.formInline);
            editRecommendhall(this.formInline).then(res => {
                this.btnLoading = false;
                if (res.code === 0) {
                    this.$message.success('操作成功');
                    this.dialog = false;
                    this.$emit('success');
                } else {
                    this.$message.error(res.message);
                }
            });
        },
        limitTimeChange() {
            this.handleVerify("time");
            if (this.limitTime === 1) {
                this.temporary.begintime = this.formInline.begintime;
                this.temporary.endtime = this.formInline.endtime;
                this.formInline.begintime = "";
                this.formInline.endtime = "";
            } else {
                this.formInline.begintime = this.temporary.begintime;
                this.formInline.endtime = this.temporary.endtime;
            }
        },
        // 提交信息
        onSubmit() {
            this.$refs.formInline.validate((valid) => {
                if (valid) {
                    if (this.type === "add") {
                        // 新增
                        upload(formatFile(this.formInline.photo)).then(res => {
                            this.formInline.photo = res.data.path;
                            this.addBanner();
                        });
                    } else {
                        // 编辑
                        if (Object.prototype.toString.call(this.formInline.photo).slice(8, -1) !== "String") {
                                upload(formatFile(this.formInline.photo)).then(res => {
                                this.formInline.photo = res.data.path;
                                this.editBanner();
                            });
                        } else {
                            this.editBanner();
                        }
                    }
                } else {
                    this.$message.warning("请填写完整的信息");
                }
            });
            this.$emit('success');
        }
    }
}
</script>

<style>
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 50px;
        height: 50px;
        line-height: 50px;
        text-align: center;
    }
    .avatar {
        width: 50px;
        height: 50px;
        display: block;
    }
</style>


